package com.edais.service.imp.gift;

import com.edais.dao.RateRisesCouponsDao;
import com.edais.domain.RateRisesCoupons;
import com.edais.domain.User;
import com.edais.domain.gift.GiftPackageGift;
import com.edais.domain.gift.GiftPackageGiftOrder;
import com.edais.service.ActivityService;
import com.edais.service.GiftExchangeFunction;
import com.edais.service.UserService;
import com.edais.service.gift.GiftPackageGiftOrderService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 加息卷
 * Created by haoyx on 2016/11/10.
 */
@Service("interestCouponImpl")
public class InterestCouponImpl implements GiftExchangeFunction {

    private static final Logger logger = Logger.getLogger(InterestCouponImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RateRisesCouponsDao rateRisesCouponsDao;

    @Autowired
    private GiftPackageGiftOrderService orderService;
    
    @Autowired
	private ActivityService activityService;

    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
    public Map<String,String> apply(Map<String,Object> params) throws Exception {

        Map<String, String> resMap = new HashMap<String, String>();
        String error = validParams(params);
        if(!StringUtils.isEmpty(error)){
            logger.info(error);
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,error);
            resMap.put("error",error);
            return resMap;
        }

        //参数获取
        GiftPackageGift giftPackageGift = (GiftPackageGift)params.get("giftPackageGift");
        Long packageOrderId = Long.valueOf(params.get("packageOrderId").toString());
        Long userId = Long.parseLong(params.get("userId").toString());
        String mobile = String.valueOf(params.get("mobile"));
        String rateRises = params.get("rateRises").toString();
        Integer riseDays = Integer.valueOf(params.get("riseDays").toString());
        Integer period = Integer.valueOf(params.get("period").toString());
        String productId = params.get("productId").toString();

        final String logInfo = "加息卷" + giftPackageGift.getId() + userId + "-";

        logger.info(logInfo+"开始");

        User user = this.userService.selectUser(userId,mobile);
        if(null == user){
            logger.info(logInfo+"查询不到此用户");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(),Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,"查询不到此用户");
            resMap.put("error",error);
            return resMap;
        }

        Date nowDate =  this.userService.getSysdate();

        //生成订单
        GiftPackageGiftOrder order = this.orderService.generateOrder(logInfo,packageOrderId,user,giftPackageGift,nowDate);

        //送加息卷
        this.insertRateRisesCoupons(logInfo,user,nowDate,productId,period,riseDays,rateRises);

        logger.info(logInfo+"成功");
        return resMap;
    }

    /**
     * 生成加息券
     * @param loginfo       日志头
     * @param user              用户
     * @param nowDate   当前时间
     * @param productId          产品ID
     * @param period        到期时长
     * @param riseDays      加息天数
     * @param rateRises     加息利率
     */
    private void insertRateRisesCoupons(String loginfo, User user, Date nowDate, String productId,Integer period,Integer riseDays,String rateRises)
    {
        try {
            RateRisesCoupons rateRisesCoupons = new RateRisesCoupons();
            rateRisesCoupons.setUser_id(Long.valueOf(user.getId()));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            nowDate = sdf.parse(sdf.format(nowDate));
            Calendar cal = Calendar.getInstance();
            cal.setTime(nowDate);
            cal.add(Calendar.DATE, period - 1);
            rateRisesCoupons.setValidity_period(cal.getTime());

            rateRisesCoupons.setProduct_id(productId);
            rateRisesCoupons.setRate_rises_days(riseDays);
            rateRisesCoupons.setRate_rises(new BigDecimal(rateRises));
            rateRisesCoupons.setGet_way("13");
            rateRisesCoupons.setStatus("0");
            rateRisesCoupons.setCreate_time(new Date());
            rateRisesCoupons.setMobile(user.getMobile());
            
            //新增--start
            //短期标加息天数 根据参数控制，0－表示不启用，1－表示启用短期标送加息券
    		String fhjxqControl=activityService.findParamValueByName("fhjxq_control");
            if("1".equals(fhjxqControl)&& "108".equals(productId)){
            	rateRisesCoupons.setRemanDays(riseDays);
            }else{
            	rateRisesCoupons.setRemanDays(0);
            }
            //新增--end
            
            rateRisesCouponsDao.insertRateRisesCoupons(rateRisesCoupons);
        } catch (Exception e) {
            logger.error(loginfo+"生成加息券错误："+e);
        }
    }

    @Override
    public String validParams(Map<String,Object> params) {
        if(null == params || params.isEmpty())
            return "参数列表不能为空";
        if(!params.containsKey("giftPackageGift") || null == params.get("giftPackageGift"))
            return "参数giftPackageGift不能为空";
        if(!params.containsKey("packageOrderId")  || StringUtils.isEmpty(params.get("packageOrderId")))
            return "参数packageOrderId不能为空";
        if(!params.containsKey("userId")  || StringUtils.isEmpty(params.get("userId")))
            return "参数userId不能为空";
        if(!params.containsKey("mobile")  || StringUtils.isEmpty(params.get("mobile")))
            return "参数mobile不能为空";
        if(!params.containsKey("rateRises")  || StringUtils.isEmpty(params.get("rateRises")))
            return "参数rateRises不能为空";
        if(!params.containsKey("riseDays")  || StringUtils.isEmpty(params.get("riseDays")))
            return "参数riseDays不能为空";
        if(!params.containsKey("period")  || StringUtils.isEmpty(params.get("period")))
            return "参数period不能为空";
        if(!params.containsKey("productId")  || StringUtils.isEmpty(params.get("productId")))
            return "参数productId不能为空";
        return null;
    }


}
